<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="客户信息">
              <el-input v-model="query.info" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="咨询渠道">
              <el-select v-model="query.channel" clearable :style="{ width: '100%' }" filterable>
                <el-option-group v-for="group in channelOptions" :key="group.id" :label="group.fullName">
                  <el-option v-for="item in group.children" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="咨询内容">
              <el-input v-model="query.content" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="咨询日期">
              <el-date-picker v-model="query.time" type="daterange" value-format="yyyy-MM-dd" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}</el-button>
<!--              <button @click="getLocation">获取当前位置</button>-->
<!--              <div v-if="error" style="color: red">{{ error }}</div>
              <div v-if="loading">正在获取位置...</div>
              <div v-if="coordinates">
                纬度: {{ coordinates.lat }}, 经度: {{ coordinates.lng }}
              </div>-->
              <!-- <el-button type="text" icon="el-icon-arrow-down" @click="showAll=true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll=false" v-else>收起</el-button> -->
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div class="left-btn"></div>
          <!-- <div>
            <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>
          </div> -->
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list" :columnData="columnList">
          <template v-for="(item, index) in columnList">
            <template v-if="item.prop === 'channel'">
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" v-if="custom.hasP(item.prop)">
                <template slot-scope="scope">
                  {{ scope.row[item.prop] | dynamicTreeCodeText(channelOptions) }}
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column :prop="item.prop" :label="item.label" :key="index" :align="item.align" :width="item.width" :show-overflow-tooltip="item.overflow || true" :fixed="item.fixed" v-if="custom.hasP(item.prop)" :formatter="item.formatter" />
            </template>
          </template>

          <el-table-column label="操作" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button type="text" size="mini" @click="handleDel(scope.row.id)" class="cu-table-delBtn">删除</el-button>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <custom-form v-if="formVisible" ref="CustomForm" @refresh="search" />
  </div>
</template>
<script>
import CustomForm from './Form'
import { getConsultList, delConsult } from '@/api/crm/consult'
export default {
  components: { CustomForm },
  data() {
    return {
      coordinates: null,
      error: null,
      loading: false,
      showAll: false,
      query: {
        info: undefined,
        time: undefined,
        channel: undefined,
        content: undefined
      },
      defaultProps: {
        value: 'id',
        children: 'children',
        label: 'fullName',
        disabled: 'selectable'
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'time'
      },
      formVisible: false,
      columnList: [{ prop: 'info', label: '客户信息', width: '200px' }, { prop: 'time', label: '咨询时间', align: 'center', width: '120px', formatter: this.custom.tableDateTimeFormat }, { prop: 'channel', label: '咨询渠道', width: '200px' }, { prop: 'content', label: '咨询内容' }, { prop: 'createTime', label: '创建时间', align: 'center', width: '120px', formatter: this.custom.tableDateTimeFormat }, { prop: 'createUserName', label: '创建用户', width: '80px' }],
      channelOptions: []
    }
  },
  computed: {},
  created() {
    this.initData()
    this.getChannelOptions()
  },
  methods: {
    getLocation() {
      this.loading = true;
      this.error = null;

      if (!navigator.geolocation) {
        this.error = "您的浏览器不支持地理定位功能";
        this.loading = false;
        return;
      }

      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.coordinates = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          this.loading = false;
        },
        (error) => {
          switch (error.code) {
            case error.PERMISSION_DENIED:
              this.error = "用户拒绝了位置请求权限";
              break;
            case error.POSITION_UNAVAILABLE:
              this.error = "位置信息不可用";
              break;
            case error.TIMEOUT:
              this.error = "请求位置超时";
              break;
            default:
              this.error = "获取位置时发生未知错误";
          }
          this.loading = false;
        },
        {
          enableHighAccuracy: true, // 高精度模式
          timeout: 5000,           // 超时时间（毫秒）
          maximumAge: 0            // 不缓存位置
        }
      );
    },
    getChannelOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'ConsultChannels' }).then(res => {
        this.channelOptions = res
      })
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      getConsultList(query)
        .then(res => {
          this.list = res.data.list
          this.total = res.data.pagination.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          delConsult(id).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    }
  }
}
</script>
